package com.hjy.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class ReadClient {
    //channel 关闭是走异步线程  EventLoopGroup 中的线程
    //如果想要再关闭之后处理一些后续的事情，可以  获取 Future 或者添加 监听，再回调事件中处理
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        channelFuture.sync();//同步操作，不用监听获取
        Channel channel = channelFuture.channel();
        Scanner scanner = new Scanner(System.in);
        //创建一个线程用于输入并向服务器发送
        new Thread(
                ()->{
                    while (true){
                        //获取到  输入内容
                        String msg = scanner.next();
                        if("q".equals(msg)){
                            channel.close();//关闭线程是再异步处理的
                            break;
                        }
                        channel.writeAndFlush(msg);
                    }
                },"input thread"
        ).start();
        //可以使用 closeFuture.addListener  回调中处理也行
        //获取closeFuture 对象
        ChannelFuture closeFuture = channel.closeFuture();
        System.out.println("waiting close event ...");
        //同步等待关闭操作
        closeFuture.sync();
        //关闭之后的一些操作
        System.out.println("关闭之后做的事情在这里");
        //关闭 EventLoopGroup
        group.shutdownGracefully();
    }
}
